import threading
import time
from operation.logging import Logging

Lock = threading.Lock()


class WriteThreadPneumatic(threading.Thread):

    def __init__(self, ser, data):
        super().__init__()
        self.serial = ser
        self.data = data
        self.daemon = True

    def run(self):
        Lock.acquire()
        self.serial_write(self.serial, self.data)
        time.sleep(0.2)
        Lock.release()

    @staticmethod
    def serial_write(ser, data):
        try:
            if data and ser.isOpen():
                ser.write(data)
        except Exception as e:
            Logging.logger.exception(e)


class WriteThreadArduino(threading.Thread):
    def __init__(self, ser, data):
        super().__init__()
        self.serial = ser
        self.data = data
        self.daemon = True

    def run(self):
        Lock.acquire()
        self.serial_write(self.serial, self.data)
        Lock.release()

    @staticmethod
    def serial_write(ser, data):
        try:
            if data and ser.isOpen():
                data = data.encode('utf-8')
                ser.write(data)
        except Exception as e:
            Logging.logger.exception(e)
